#!/usr/bin/python
# -*- coding: utf-8 -*-

import threading

class properties(object):
    def __init__(self):
        from GUI.dapi.models import Var
        self.varss=Var.objects.all()
    @property
    def WEB_SOCKET_PORT(self):
        return self.varss.filter(name="WEB_SOCKET_PORT")
    @property
    def SERIAL_SOCKET_PORT(self):
        return self.varss.filter(name="SERIAL_SOCKET_PORT")
    @property
    def WEB_SOCKET_PORT_STATUS(self):
        return self.varss.filter(name="WEB_SOCKET_PORT_STATUS")
    @property
    def SERIAL_SOCKET_PORT_STATUS(self):
        return self.varss.filter(name="SERIAL_SOCKET_PORT_STATUS")

class QueryManagerForDjango:


    def __init__(self,autostart=True,debuglevel="info"):
        self.autostart=autostart
        self.debuglevel=debuglevel
        self.__startCeleryD__()
        if self.autostart:
            self.GUI.start()
            
            
            
    def __celeryInThread__(self):
        import os
        init_command="python GUI/manage.py celeryd -l %s --settings=settings -E" % (self.debuglevel)
        print "try to run %s" % init_command
        os.system(init_command)
        
        
    def __startCeleryD__(self):
        self.GUI=threading.Thread(target=self.__celeryInThread__, args=())
        
        


class DjangoServer:
    def __init__(self,autostart=True):
        self.properties=properties()
        self.autostart=autostart
        self.init_django_server()
        self.Celery=QueryManagerForDjango(self.autostart)
        if self.autostart:
            self.GUI.start()



        
    def __djangoInThread__(self):
        import os
        init_command="python GUI/manage.py runserver 0.0.0.0:8000"
        print "try to run %s" % init_command
        os.system(init_command)

        
        
    def init_django_server(self):
        self.GUI=threading.Thread(target=self.__djangoInThread__, args=())

    
